<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Base\BaseController;
use App\Models\Pay;
use App\Models\User;

// require_once '../../Library/Wechat/lib/WxPay.Config.php';
// require_once '../../Library/Wechat/lib/WxPay.Api.php';
// require_once '../../Library/Wechat/WxPay.JsApiPay.php';

require_once '../app/Library/Wechat/lib/WxPay.Config.php';
require_once '../app/Library/Wechat/lib/WxPay.Api.php';
require_once '../app/Library/Wechat/WxPay.JsApiPay.php';

class PayController extends BaseController
{

	// 规定为空参数
	protected function rules($methodname)
    {
        switch ($methodname) {
            case 'jsapi':
               	$params = ['token'=>'required',
               		'total' => 'required',
               		'item_id' => 'required',
               		'item_type' => 'required',
               		'user_id' => 'required',
               		'trader_id' => 'required'
               	];
                break;
        }
        return $params;
    }

    public function jsapi(Request $request){
    	$payment_id = "P".date("YmdHis").substr(md5(microtime()),0,6);

    	$item_id = $request->input('item_id');
		$item_type = $request->input('item_type');
    	$total = $request->input('total');
		$user_id = $request->input('user_id');
		$trader_id = $request->input('trader_id');


		$payment_input = [
			'payment_id' => $payment_id,
            'item_id' => $item_id,
            'item_type' => $item_type,
            'total' => $total,
            'user_id' => $user_id,
            'trader_id' => $trader_id
        ];

        $payment = Pay::create($payment_input);
        $payment->status = 0;
        $payment->save();


        //①、获取用户openid
		$tools = new \JsApiPay();

		// $openId = $tools->GetOpenid();
		$userInfo = User::find($user_id);
		$openid = $userInfo->openid;

		//②、统一下单
		$input = new \WxPayUnifiedOrder();
		$input->SetBody("test");
		$input->SetAttach('test');
		$input->SetOut_trade_no($payment_id);
		// $input->SetTotal_fee($total * 100); //单位是分
		$input->SetTotal_fee("1");
		$input->SetTime_start(date("YmdHis"));
		$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag($payment_id);
		$input->SetNotify_url(url('pay/notify'));
		$input->SetTrade_type("JSAPI");
		$input->SetOpenid($openId);
		$order = \WxPayApi::unifiedOrder($input);
		// echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
		// printf_info($order);
		$jsApiParameters = $tools->GetJsApiParameters($order);

		return array('code' => config('constants.API_SUCCESS_CODE'),'message' => config('constants.API_SUCCESS'),'jsApiParameters' => $jsApiParameters);

    }

    public function notify(){
    	$notify = new \PayNotifyCallBack();
		$notify->Handle(false);
		$result = \WxpayApi::notify(array($this, 'payment_notify'), $msg);
	}

public function payment_notify($data)
	{
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		else if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		else{
			$payment_id = $data["out_trade_no"];
			$payment = Pay::where('payment_id',$payment_id)->first();
			$payment->status = 1;
			$payment->save();
		}

	}

	public function Queryorder($transaction_id)
	{
		$input = new \WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = \WxPayApi::orderQuery($input);
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}

}
